﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLBH.Base;
using QLBH.DataModel;
using QLBH.Model.Controller;
using QLBH.Category;
using QLBH.StandardUI;
using QLBH.FeatureBase;
using CrystalDecisions.CrystalReports.Engine;
using QLBH.Reports;
using System.Data.Objects.DataClasses;
using System.Data.SqlTypes;
using QLBH.ModelInterface;

namespace QLBH.SaleProduct
{
    public partial class PhieuMuaHangDlg : Form,IReportable
    {
        private eDlgType dlgType;

        public eDlgType DlgType
        {
            get { return dlgType; }
            set 
            { 
                dlgType = value; 

                if (dlgType==eDlgType.ADD)
                {
                    this.Text = "Thêm mới phiếu mua hàng";
                }
                else
                {
                    this.Text = "Cập nhật thông tin phiếu mua hàng";
                }                
            }
        }
        private IPhieuMuaHangChiTietModel model;

        public IPhieuMuaHangChiTietModel Model
        {
            get { return model; }
            set 
            {
                model = value;               
                InitDataForControl();                 
            }
        }
        private ListView listViewPopup;
        private List<MATHANG> mathangs;
        private MATHANG selected;
        private IMatHangItemModel editItem;
        private eDlgType functionType = eDlgType.ADD;
        
        //MatHangItemModel newItem = new MatHangItemModel();
        private KHO khoHang;      
        public PhieuMuaHangDlg()
        {
            InitializeComponent();

            listViewPopup = new ListView();

            listViewPopup.View = View.Details;
            listViewPopup.Width = 500;


            listViewPopup.Height = 300;

            listViewPopup.Columns.Add("Mã MH", 150, HorizontalAlignment.Left);
            listViewPopup.Columns.Add("Tên MH", 350, HorizontalAlignment.Left);

            listViewPopup.MultiSelect = false;
            listViewPopup.GridLines = true;
            listViewPopup.FullRowSelect = true;

           // dataGridViewEx1.PopupControl = listViewPopup;

            //dataGridViewEx1.FilterContent += dataGridViewEx1_FilterContent;
            listViewPopup.SelectedIndexChanged += listViewPopup_SelectedIndexChanged;            

            mathangs = MatHangController.GetInstance().GetAll().ToList();

            cmbMatHang.DropDownControl = listViewPopup;

            tbxMatHangSeach.PopupControl = listViewPopup;
            tbxMatHangSeach.DataFilterEvent += new EventHandler(autoCompleteTextBox1_DataFilterEvent);

            tbxSoLuong.MouseClick += new MouseEventHandler(tbxSoLuong_MouseClick);

            int formHeight = Screen.PrimaryScreen.WorkingArea.Height;
            if (Height<formHeight*0.8)
            {
                Height = (int)(formHeight * 0.8);
            }
      
        }

        void tbxSoLuong_MouseClick(object sender, MouseEventArgs e)
        {
            tbxSoLuong.SelectAll();
        }
        void autoCompleteTextBox1_DataFilterEvent(object sender, EventArgs e)
        {
            TextBox editTbx = (TextBox)sender;

            var items = mathangs.Where(mh => mh.MHTEN.Contains(editTbx.Text) || mh.MHCODE.Contains(editTbx.Text)).ToList();

            BuildListViewPopupItems(items);
        }
        void listViewPopup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewPopup.SelectedItems.Count>0)
            {                                        
                String mhID = listViewPopup.SelectedItems[0].SubItems[0].Text;                
                MATHANG mh = MatHangController.GetInstance().FindBy(h => h.MHCODE == mhID).FirstOrDefault();
                
                if (mh!=null)
                {
                    selected = mh;
                    tbxMatHangSeach.Text = selected.MHTEN;
                    tbxSoLuong.Text = "1";                                            
                }
                listViewPopup.Visible = false;
                tbxSoLuong.SelectAll();
                tbxSoLuong.Focus();
                Control dd = ActiveControl;
            }                                                                 
        }
        private void SetDataForGrid()
        {
            matHangItemModelBindingSource.DataSource = new BindingList<IMatHangItemModel>(model.MatHang);

            dataGridView1.DataSource = matHangItemModelBindingSource;

            matHangIDDataGridViewTextBoxColumn.Visible = false;

            decimal totalMoney = 0;
            foreach (IMatHangItemModel item in model.MatHang)
            {
                totalMoney += item.ThanhTien;
            }
            lbTongTien.Text = totalMoney.ToString();

            model.TongTien = totalMoney;
        }

        void dataGridViewEx1_FilterContent(object sender, EventArgs e)
        {
            

        }
        private void BuildListViewPopupItems(List<MATHANG> mathangs)
        {            
            listViewPopup.Items.Clear();
             foreach (MATHANG mh in mathangs)
             {
                 ListViewItem item = new ListViewItem();
                 item.Text = mh.MHCODE;
                 item.SubItems.Add(mh.MHTEN);

                 listViewPopup.Items.Add(item);
             }
        }
               
        private void InitDataForControl()
        {
            lbSoPhieu.Text = model.SoPhieu;
            lbNguoiTao.Text = model.UserName;
            lbNgayTao.Text = model.NgayTao.ToShortDateString();
            if (model.NgayGui != SqlDateTime.MinValue.Value)
            {
                lbNgayGui.Text = model.NgayGui.ToShortDateString();
            }
            else
            {
                lbNgayGui.Text = "";
            }                                   

            List<KHO> khos = KhoController.GetInstance().GetAll().ToList();

            cmbTenKho.DataSource = khos;

            cmbTenKho.DisplayMember = "TENKHO";

            if (dlgType==eDlgType.ADD)
            {
                KHO defaultKho = khos.Where(k => k.MACDINH == true).FirstOrDefault();
                if (defaultKho != null)
                {
                    cmbTenKho.SelectedItem = defaultKho;
                }

                if (cmbTenKho.SelectedItem != null)
                {
                    khoHang = cmbTenKho.SelectedItem as KHO;
                }
            }
            else
            {
                khoHang = khos.Find(kh => kh.KHOID == model.MaKho);
                if (khoHang!=null)
                {
                    cmbTenKho.SelectedItem = khoHang;
                }
            }
            
            

            SetDataForGrid();
            
        }

        private void cmbMatHang_TextChanged(object sender, EventArgs e)
        {
            if (!cmbMatHang.DroppedDown)
            {
                cmbMatHang.DroppedDown = true;
                cmbMatHang.Focus();
            }
            
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                DataInputHelper.CheckIntValue(tbxSoLuong.Text, "Số lượng");
            }
            catch (System.Exception ex)
            {
                ShowMessage.Instance.ShowError(ex.Message);
                tbxSoLuong.SelectAll();
                tbxSoLuong.Focus();
                return;
            }
            if (functionType==eDlgType.ADD)
            {
                if (selected != null)
                {
                    IMatHangItemModel item = ModelFactory.ModelFactory.GetMatHangItemModelInstance();
                    item.InitFromMatHangModel(selected);
                    int soluong = int.Parse(tbxSoLuong.Text);
                    item.SoLuong = soluong;

                    if (model.MatHang.Where(mh => mh.MaMH == item.MaMH).FirstOrDefault() != null)
                    {
                        ShowMessage.Instance.ShowError("Mặt hàng đã tồn tại, bạn cần chọn và cập nhật thông tin mặt hàng từ DS mặt hàng");
                        tbxMatHangSeach.SelectAll();
                        tbxMatHangSeach.Focus();
                        return;
                    }

                    model.MatHang.Add(item);
                    //model.MatHang.Add(newItem);

                    SetDataForGrid();
                    tbxMatHangSeach.Focus();
                }
            }
            else
            {
                //Edit
                int soluong = int.Parse(tbxSoLuong.Text);
                editItem.SoLuong = soluong;

                //model.MatHang.Remove(newItem);
                SetDataForGrid();
                tbxMatHangSeach.Enabled = true;
                tbxMatHangSeach.Focus();

                btnAdd.Text = "Thêm";
                btnAdd.Image = global::QLBH.SaleProduct.Properties.Resources.add_1_icon;
                functionType = eDlgType.ADD;
            }
        }

        private void tbxMatHangSeach_KeyDown(object sender, KeyEventArgs e)
        {
           
        }

        private void PhieuMuaHangDlg_KeyDown(object sender, KeyEventArgs e)
         {
            switch(e.KeyCode)
            {
                case Keys.F1:
                    tbxMatHangSeach.SelectAll();
                    tbxMatHangSeach.Focus();
                    break;
                case Keys.F2:
                    tbxSoLuong.Focus();
                    tbxSoLuong.Focus();
                    break;
                case Keys.F3:
                case Keys.Enter:
                    btnAdd_Click(btnAdd, null);
                    break;
                case Keys.Delete:
                    if (btnDelete.Enabled)
                    {
                        btnDelete_Click(null, null);
                    }
                    break;
                case Keys.F4:                    
                    cmbTenKho.DroppedDown = true;
                    break;
                case Keys.S:
                    if (e.Control)
                    {
                        tsbtnSave_Click(null, null);
                    }
                    break;
                case Keys.P:
                    if (e.Control)
                    {
                        tsbtnPrinter_Click(null, null);
                    }
                    break;
                case Keys.Escape:
                    this.Close();
                    break;
                    

            }

        }        

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                IMatHangItemModel itemSelected = dataGridView1.SelectedRows[0].DataBoundItem as IMatHangItemModel;

                if (itemSelected != null)
                {
                    editItem = itemSelected;
                    tbxMatHangSeach.SetText(editItem.TenMH);
                    tbxSoLuong.Text = editItem.SoLuong.ToString();

                    btnAdd.Text = "Sửa";
                    functionType = eDlgType.EDIT;
                    this.btnAdd.Image = global::QLBH.SaleProduct.Properties.Resources.edit_icon;

                    tbxSoLuong.SelectAll();
                    tbxSoLuong.Focus();

                    tbxMatHangSeach.Enabled = false;
                }
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {

                btnDelete.Enabled = true;

            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                btnDelete.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow obj in dataGridView1.SelectedRows)
                {

                    model.MatHang.Remove(obj.DataBoundItem as IMatHangItemModel);

                }                
               // model.MatHang.Remove(newItem);
                SetDataForGrid();
                editItem = null;
            }
        }

        private void lbAddKho_Click(object sender, EventArgs e)
        {
            AddKhoDlg addKho = new AddKhoDlg();
            addKho.DlgType=eDlgType.ADD;

            if (addKho.ShowDialog()==DialogResult.OK)
            {
                List<KHO> khos = KhoController.GetInstance().GetAll().ToList();

                cmbTenKho.DataSource = khos;

                cmbTenKho.DisplayMember = "TENKHO";

                cmbTenKho.SelectedItem = addKho.Model;
            }
        }

        private void cmbTenKho_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (khoHang != null && khoHang != cmbTenKho.SelectedItem as KHO && model.MatHang.Count > 0)
            {
                DialogResult result = MessageBox.Show("Phiếu mua hàng bạn đang lập cho kho cũ sẽ bị xóa, bạn có muốn tiếp tục không?",
                "Đổi kho hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    model.MatHang.Clear();
                    khoHang = cmbTenKho.SelectedItem as KHO;
                    SetDataForGrid();
                }
                else
                {
                    cmbTenKho.SelectedItem = khoHang;
                }
            }
            
        }

        private void tsbtnSave_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {                
                PHIEUMUAHANG entity = (model as IPhieuMuaHangModel).ToEntity();
                if (dlgType==eDlgType.ADD)
                {
                    entity.MUAHANGID = Guid.NewGuid();
                }                                                     

                if (entity.PHIEUMUAHANGCTs==null)
                {
                    entity.PHIEUMUAHANGCTs = new EntityCollection<PHIEUMUAHANGCT>();
                    
                }
                foreach (IMatHangItemModel mh in model.MatHang)
                {
                    PHIEUMUAHANGCT mhct = mh.ToEntity();
                    entity.PHIEUMUAHANGCTs.Add(mhct);
                }
                if (dlgType == eDlgType.ADD)
                {
                    entity = PhieuMuaHangController.GetInstance().Add(entity);
                }
                else
                {
                    entity = PhieuMuaHangController.GetInstance().Edit(entity);
                }
                
            }
            catch (System.Exception ex)
            {
                ShowMessage.Instance.ShowError(ex.Message);
            }
            this.Cursor = Cursors.Default;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void tsbtnPrinter_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            ReportDocument doc = BuildReportDocument();
            ShowPrintDlg(doc);
            this.Cursor = Cursors.Default;
        }
        private void ShowPrintDlg(ReportDocument rp)
        {
            PrintDialog printDlg = new PrintDialog();
            printDlg.AllowSomePages = true;

            if (printDlg.ShowDialog(this) == DialogResult.OK)
            {
                int nCopies = printDlg.PrinterSettings.Copies;
                int startPage = printDlg.PrinterSettings.FromPage;
                int toPage = printDlg.PrinterSettings.ToPage;
                bool collated = printDlg.PrinterSettings.Collate;

                System.Drawing.Printing.PrinterSettings printerSetting = printDlg.PrinterSettings;
                try
                {
                    rp.PrintOptions.PrinterName = printerSetting.PrinterName;
                    rp.PrintToPrinter(nCopies, collated, startPage, toPage);
                }
                catch (System.Exception ex)
                {
                    ShowMessage.Instance.ShowError(ex.Message);
                }
            }
        }

        public ReportDocument BuildReportDocument()
        {
            ReportDocument doc = ReportLoader.GetReport(eReportTypes.RP_MUAHANGCHITIET);
            if (doc != null)
            {
                //Set data source for reports
                PhieuMHChiTiet ds = new PhieuMHChiTiet();
                IPhieuMuaHangModel phieuMuaHang = model as IPhieuMuaHangModel;
                phieuMuaHang.MaPhieu = Guid.NewGuid();

                DataTable dt1 = DataSourceHelper.ToDataTable(new List<IPhieuMuaHangModel>() { phieuMuaHang });
                DataTable dt2 = DataSourceHelper.ToDataTable(model.MatHang);
                ds.PhieuMuaHang.Merge(dt1);
                ds.DSMatHang.Merge(dt2);
                doc.SetDataSource(ds);
                doc.SetParameterValue("CompanyName", "Công ty TNHH MED-AID");
                doc.SetParameterValue("Address", "Lô 12, BT1, X2, Bắc linh đàm, Hoàng Mai, Hà Nội");
            }
            else
            {
                ShowMessage.Instance.ShowError("Không tìm thấy báo cáo!");
            }
            return doc;
        }

        private void btnPrinPreview_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            ReportDocument doc = BuildReportDocument();
            ReportDialogBase report = new ReportDialogBase(doc);
            report.ShowDialog();
            this.Cursor = Cursors.Default;
        }
    }
}
